package com.interview.ujiuye3;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * Copyright (C), 2018-2020
 * FileName: SpinLockDemo
 * Author:   kongfanyu
 * Date:     2020/10/13 15:19
 */
public class SpinLockDemo {

    private AtomicReference<Thread> atomicReference = new AtomicReference<>();

    public void mylock(){
        Thread thread = Thread.currentThread();//获取当前线程
        System.out.println(thread.getName() + "come in .....");
        while( !atomicReference.compareAndSet(null,thread) ){

        }
        System.out.println(thread.getName() +"获取锁对象.....");
    }

    public void myUnlock(){
        Thread thread = Thread.currentThread();
        atomicReference.compareAndSet(thread,null);
        System.out.println(thread.getName() +"\t释放锁对象...");

    }

    public static void main(String[] args) {
        SpinLockDemo spinLockDemo = new SpinLockDemo();//创建对象
        new Thread( () ->{
            spinLockDemo.mylock();//占有锁对象
            try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); }
            spinLockDemo.myUnlock();//释放锁对象
        }, "AAA").start();
        //让主线程休眠1秒
        try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
        //第二个线程
        new Thread( () ->{
            spinLockDemo.mylock();//获取锁对象
            spinLockDemo.myUnlock();//释放锁对象
        },"BBB" ).start();
    }
}
